package handler

import (
	"art-mng-sys/model"
	"github.com/gin-gonic/gin"
	"strconv"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	var article []model.Article
	offset := (page - 1) * size
	err := model.DB.Offset(offset).Limit(size).Find(&article).Error
	var total int64
	model.DB.Model(&article).Count(&total)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"mgs":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code":  200,
			"mgs":   "查询成功",
			"data":  article,
			"total": total,
		})
		return
	}
}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	author := c.PostForm("author")
	content := c.PostForm("content")
	data := model.Article{
		Title:   title,
		Author:  author,
		Content: content,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"mgs":  "添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"mgs":  "添加成功",
		})
		return
	}
}
